package com.cysion.study.ui.fragment

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.entity.AddressBean
import com.cysion.study.entity.AddressInfoPO
import com.cysion.study.entity.Child
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.ui.PClockinMapActivity
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.study.widget.downmenu.MenuItem
import com.cysion.study.widget.downmenu.MenuItem1
import com.cysion.study.widget.downmenu.SimpleDropDownMenu
import com.cysion.study.widget.downmenu.SimpleDropDownMenu1
import com.cysion.targetfun._subscribe
import kotlinx.android.synthetic.main.activity_pmanager_info.*

class PManagerInfoActivity : BaseActivity(), View.OnClickListener {
    override fun getLayoutId(): Int {
        return R.layout.activity_pmanager_info
    }

    private var ifFmleduInfo = ""
    override fun initView() {
        ifFmleduInfo = intent.extras.getString("ifFmleduInfo")
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            setTitle("家教信息")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }

        tv_submit.setOnClickListener(this)
        tv_supplement.setOnClickListener(this)
        initDropDownMenu()//初始化下拉框

        getCategoryList()//获取科目分类


    }

    override fun initData() {
        super.initData()
        loadProviceData()

    }



    var keChild = mutableListOf<Child>()
    //城市
    var cityList = mutableListOf<MenuItem>()
    var cityTitle: MenuItem = MenuItem(0, "请选择", "")

    //补习时间
    var timeList = mutableListOf<MenuItem1>()
    var timeTitle: MenuItem1 = MenuItem1(0, "请选择", "", false, keChild)

    //授课方式
    var typeList = mutableListOf<MenuItem1>()
    var typeTitle: MenuItem1 = MenuItem1(0, "请选择", "", false, keChild)

    //科目
    var keList = mutableListOf<MenuItem1>()

    var ketitle: MenuItem1 = MenuItem1(0, "请选择", "", false, keChild)
    private fun initDropDownMenu() {
        sm_ke.showImgIcon(false)//科目
        sm_ke.clickItemCloseMenu = false
        sm_ke.setOnClickListener(this)
        sm_ke.ShowOneIcon(false)//\ //isShowChild =true  处理一级点击返回
        /* keList.add(MenuItem(0,"小学","1"))
         keList.add(MenuItem(0,"初中","2"))
         keList.add(MenuItem(0,"高中","3"))
         keList.add(MenuItem(0,"音乐","4"))*/
        sm_ke.addMenuItemForTitle(keList, ketitle)
        sm_ke.menuItemClickListener = object : SimpleDropDownMenu1.OnMenuItemClickListener {
            override fun onMenuItemClickListener(v: View, position: Int) {
                /*sm_ke.setTitleItem(
                    MenuItem1(0, keList.get(position).itemTitle,
                        keList.get(position).itemId, false, keChild)
                )
                categoryIds = keList.get(position).itemId
                categoryNames = keList.get(position).itemTitle*/
            }

            override fun onMenuClick(name: String, ids: String) {
                if (TextUtils.isEmpty(name)) {
                    sm_ke.setTitleItem(MenuItem1(0, "请选择", "", false, keChild))
                } else {
                    sm_ke.setTitleItem(MenuItem1(0, name, ids, false, keChild))
                    categoryIds = ids
                    categoryNames = name
                }

//                println("###选择的科目=" + name + ids)
            }
        }


        sm_city.showImgIcon(false)//
        sm_city.setOnClickListener(this)
        cityList.add(MenuItem(0, "青岛", "118"))
        sm_city.addMenuItemForTitle(cityList, cityTitle)
        sm_city.menuItemClickListener = object : SimpleDropDownMenu.OnMenuItemClickListener {
            override fun onMenuItemClickListener(v: View, position: Int) {
                sm_city.setTitleItem(
                    MenuItem(0, cityList.get(position).itemTitle, cityList.get(position).itemId)
                )
                cityId = cityList.get(position).itemId
                cityName = cityList.get(position).itemTitle
            }

        }

        //授课方式
        sm_type.showImgIcon(false)//
        sm_type.setOnClickListener(this)
        sm_type.ShowOneIcon(true)//\ //isShowChild =true  处理一级点击返回
        sm_type.clickItemCloseMenu = true
        typeList.add(MenuItem1(0, "到学生家授课", "1", false, keChild))
        typeList.add(MenuItem1(0, "到老师家上课", "2", false, keChild))
        typeList.add(MenuItem1(0, "在线授课", "3", false, keChild))
        sm_type.addMenuItemForTitle(typeList, typeTitle)
        sm_type.menuItemClickListener = object : SimpleDropDownMenu1.OnMenuItemClickListener {
            override fun onMenuItemClickListener(v: View, position: Int) {
                /*sm_type.setTitleItem(
                    MenuItem1(0, typeList.get(position).itemTitle, typeList.get(position).itemId
                        , false, keChild)
                )
                types = typeList.get(position).itemTitle
                if (types == "到老师家上课" || types == "到学生家授课") {
                    ll_address.visibility = View.VISIBLE
                } else {
                    ll_address.visibility = View.GONE
                }*/
            }

            override fun onMenuClick(name: String, ids: String) {
                types = name
                if (TextUtils.isEmpty(name)) {
                    sm_type.setTitleItem(MenuItem1(0, "请选择", "", false, keChild))
                } else {
                    sm_type.setTitleItem(MenuItem1(0, name, ids, false, keChild))
                }

                println("###选择的授课方式=" + types)
                //到学生家上课，需要填写地址补充说明  到老师家上课，需要填写详细地址
                if (types.contains("到老师家上课") && types.contains("到学生家授课")) {
                    ll_supplement.visibility = View.VISIBLE//授课地址
                    ll_sup.visibility = View.VISIBLE//地址补充说明
                    ll_address.visibility = View.VISIBLE//详细地址 门牌号
                } else if (types.contains("到老师家上课")) {
                    ll_supplement.visibility = View.VISIBLE//授课地址
                    ll_address.visibility = View.VISIBLE//详细地址 门牌号
                    ll_sup.visibility = View.GONE
                } else if (types.contains("到学生家授课")) {
                    ll_sup.visibility = View.VISIBLE//地址补充说明
                    ll_supplement.visibility = View.GONE
                    ll_address.visibility = View.GONE
                } else {
                    ll_sup.visibility = View.GONE
                    ll_supplement.visibility = View.GONE
                    ll_address.visibility = View.GONE
                }
            }
        }

        //补习时间
        sm_time.showImgIcon(false)//
        sm_time.setOnClickListener(this)
        sm_time.ShowOneIcon(true)//\ //isShowChild =true  处理一级点击返回
        sm_time.clickItemCloseMenu = true//一级下拉点击事件  否的话处理子列表
        timeList.add(MenuItem1(0, "周末", "1", false, keChild))
        timeList.add(MenuItem1(0, "平日", "2", false, keChild))
        sm_time.addMenuItemForTitle(timeList, timeTitle)

        /*sm_time.checkClickListener= object : SimpleDropDownMenu1.CheckClickListener {
            override fun onItemCheck(v: View, position: Int) {

            }

        }*/
        sm_time.menuItemClickListener = object : SimpleDropDownMenu1.OnMenuItemClickListener {
            override fun onMenuItemClickListener(v: View, position: Int) {
                /*sm_time.setTitleItem(
                    MenuItem1(0, timeList.get(position).itemTitle,
                        timeList.get(position).itemId, false, keChild)
                )
                times = timeList.get(position).itemTitle*/
            }

            override fun onMenuClick(name: String, ids: String) {
                if (TextUtils.isEmpty(name)) {
                    sm_time.setTitleItem(MenuItem1(0, "请选择", "", false, keChild))
                } else {
                    sm_time.setTitleItem(MenuItem1(0, name, ids, false, keChild))
                    times = name
                }
            }
        }


    }


    //家教信息科目 分类
    private fun getCategoryList() {
      showWaitDialog(false)
        ApiClient.api.category(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {

                    println("###分类数据=" + it[0].name)
                    for (obj in it) {
                        keList.add(MenuItem1(0, obj.name, obj.id, false, obj.child))
                    }
                    sm_ke.addMenuItemForTitle(keList, ketitle)
                    //家教信息是否完善：0、代表未完善；1、代表已完善
                    if (ifFmleduInfo == "1") {
                        getData()
                    }

                }
                _onError {

                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    override fun closeMvp() {
    }

    override fun onClick(v: View?) {
        when (v?.id) {

            R.id.tv_supplement -> {//地址选择
                UIHelper.jumpForResult(self, PClockinMapActivity::class.java, 105)
            }
            R.id.tv_submit -> {
                submit()
            }
            R.id.sm_ke -> {
                sm_ke.openMenu()
            }
            R.id.sm_city -> {
                if (provinceItems == null || provinceItems.size < 1) {
                    ShowToast("地址初始化中..")
                    return
                }
                //显示选择器
                showAddressPicker(provinceItems, cityItems, areaItems)
//                sm_city.openMenu()
            }
            R.id.sm_type -> {
                sm_type.openMenu()
            }
            R.id.sm_time -> {
                sm_time.openMenu()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 105 && resultCode == Activity.RESULT_OK) {
            //地图选择地址返回
            supplement = data?.getBundleExtra("key")?.getString("address").toString()
            tv_supplement.text=supplement
        }
    }


    private fun getData() {
        ApiClient.api.familyeduInfoGetInfo(
            UserCache.token
        ).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    hideWaitDialog()
                    categoryIds=it.categoryIds
                    categoryNames=it.categoryNames
                    cityId=it.cityId
                    cityName=it.cityName
                    types=it.types
                    supplement=it.supplement
                    explanation
                    address=it.address
                    times=it.times
                    fee=it.fee

                    sm_ke.setTitleItem(MenuItem1(0, categoryNames, categoryIds, false, keChild))
                    sm_city.setTitleItem(MenuItem(0, cityName, cityId))
                    sm_type.setTitleItem(MenuItem1(0, types, "0", false, keChild))
                    sm_time.setTitleItem(MenuItem1(0, times, "0", false, keChild))

                    //到学生家上课，需要填写地址补充说明  到老师家上课，需要填写详细地址
                    if (types.contains("到老师家上课") && types.contains("到学生家授课")) {
                        ll_supplement.visibility = View.VISIBLE//授课地址
                        ll_sup.visibility = View.VISIBLE//地址补充说明
                        ll_address.visibility = View.VISIBLE//详细地址 门牌号
                    } else if (types.contains("到老师家上课")) {
                        ll_supplement.visibility = View.VISIBLE//授课地址
                        ll_address.visibility = View.VISIBLE//详细地址 门牌号
                        ll_sup.visibility = View.GONE
                    } else if (types.contains("到学生家授课")) {
                        ll_sup.visibility = View.VISIBLE//地址补充说明
                        ll_supplement.visibility = View.GONE
                        ll_address.visibility = View.GONE
                    } else {
                        ll_sup.visibility = View.GONE
                        ll_supplement.visibility = View.GONE
                        ll_address.visibility = View.GONE
                    }
                    tv_supplement.text=it.supplement
//                    et_sup.setText(it.ex)
                    et_address.setText(it.address)
                    et_money.setText(it.fee)
                }
                _onError {
                    hideWaitDialog()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }

    }


    private var categoryIds = ""//科目分类id集合，以逗号分隔
    private var categoryNames = ""//科目分类Name集合，以逗号分隔
    private var cityId = ""//
    private var cityName = ""//
    private var types = ""//补习方式集合，以逗号分隔，同时方式如下：1、到学生家授课；2、到老师家授课；3、在线授课；
    private var supplement = ""//授课地址
    private var explanation = ""//地址补充
    private var address = ""//详细地址 门牌号
    private var times = ""//补习时间集合，以逗号分隔，同时方式如下：1、周末；2、平日
    private var fee = ""//费用
    private var latitude = ""//
    private var longitude = ""//
    private fun submit() {
        if (TextUtils.isEmpty(categoryIds)) {
            UIHelper.showToast(self,"请选择授课科目")
            return
        }
        if (TextUtils.isEmpty(cityId)) {
            UIHelper.showToast(self,"请选择城市")
            return
        }

        if (TextUtils.isEmpty(types)) {
            UIHelper.showToast(self,"请选择补习方式")
            return
        }


        //到学生家上课，需要填写地址补充说明  到老师家上课，需要填写详细地址
        if (types.contains("到老师家上课") && types.contains("到学生家授课")) {
            if (TextUtils.isEmpty(supplement)) {
                UIHelper.showToast(self,"请选择授课地址")
                return
            }
            et_sup.checkBlank("请补充地址") ?: return
            et_address.checkBlank("请补充详细地址") ?: return
            explanation=et_sup.text.toString().trim()//地址补充
            address = et_address.text.toString().trim()//门牌号
        } else if (types.contains("到老师家上课")) {
            if (TextUtils.isEmpty(supplement)) {
                UIHelper.showToast(self,"请选择授课地址")
                return
            }
            et_address.checkBlank("请补充详细地址") ?: return
            address = et_address.text.toString().trim()//门牌号
        } else if (types.contains("到学生家授课")) {
            et_sup.checkBlank("请补充地址") ?: return
            explanation=et_sup.text.toString().trim()//地址补充
        }

        if (TextUtils.isEmpty(times)) {
            UIHelper.showToast(self,"请选择补习时间")
            return
        }
        et_money.checkBlank("请填写费用") ?: return

        fee = et_money.text.toString().trim()
//        Alert.loading(self)
        showWaitDialog(false)
        ApiClient.api.submitFamilyeduInfo(
            UserCache.token,
            categoryIds,
            categoryNames,
            cityId,
            cityName,
            types,
            supplement,
            explanation,
            address,
            times,
            UserCache.lat,
            UserCache.lon,
            fee
        ).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
//                    Alert.close()
                    hideWaitDialog()
                    UIHelper.showToast(self,"提交成功")
                    finish()
                }
                _onError {
//                    Alert.close()
                    hideWaitDialog()
                    UIHelper.showToast(self,ErrorHandler.handle(it).errorMsg)
                }
            }

    }

    private lateinit var pcaCodeList: List<AddressBean>
    private fun loadProviceData() {
        ApiClient.api.getAllCity(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {

                    pcaCodeList = it
                    //条件选择器
                    initAddressPicker(pcaCodeList)
                }
                _onError {

                    UIHelper.showToast(self,ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    val provinceItems = mutableListOf<AddressInfoPO>()
    val cityItems = mutableListOf<MutableList<AddressInfoPO>>()
    val areaItems = mutableListOf<MutableList<MutableList<AddressInfoPO>>>()
    // * 初始化地址数据
    private fun initAddressPicker(pcaCodeList: List<AddressBean>) {
        //Json2Bean
//        val pcaCodeList = Gson().fromJson<MutableList<PCACodePO>>(FileUtil.getAssetsFileText(mApplication, "pcacode.json"), object : TypeToken<MutableList<PCACodePO>>() {}.type)
        //遍历省
        pcaCodeList.forEach { pcaCode ->
            //存放省内市区
            val cityList = mutableListOf<AddressInfoPO>()
            //存放省内所有辖区
            val areaList = mutableListOf<MutableList<AddressInfoPO>>()
            //遍历省内市区
            pcaCode.citys.forEach { cCode ->
                //添加省内市区
                cityList.add(AddressInfoPO(cCode.id, cCode.name))
                //存放市内辖区
                val areas = mutableListOf<AddressInfoPO>()
                //添加市内辖区
                cCode.countys.forEach { addressInfo ->
                    areas.add(AddressInfoPO(addressInfo.id, addressInfo.name))
                }
                areaList.add(areas)
            }
            //添加省份
            provinceItems.add(AddressInfoPO(pcaCode.id, pcaCode.name))
            //添加市区
            cityItems.add(cityList)
            //添加辖区
            areaItems.add(areaList)
        }
        /* //显示选择器
         showAddressPicker(provinceItems, cityItems, areaItems)*/
    }

    /**
     * 显示地址选择
     */
    fun showAddressPicker(
        provinceItems: MutableList<AddressInfoPO>,
        cityItems: MutableList<MutableList<AddressInfoPO>>,
        areaItems: MutableList<MutableList<MutableList<AddressInfoPO>>>
    ) {
        //条件选择器
        val pvOptions = OptionsPickerBuilder(self,
            OnOptionsSelectListener { options1, option2, options3, v ->
                //返回的分别是三个级别的选中位置
                var tx = ""
                println("####区数据1${areaItems[options1][option2].size}")
                if (areaItems[options1][option2].size < 11) {
                    tx =
                        provinceItems[options1].pickerViewText + cityItems[options1][option2].pickerViewText
                } else {
                    tx =
                        provinceItems[options1].pickerViewText + cityItems[options1][option2].pickerViewText + areaItems[options1][option2][options3].pickerViewText
                }
//                tv_area.text = tx//山东省AddressInfoPO(id=2, name=济南2)章丘
                println("####$tx")
                println("####地址=" + cityItems[options1][option2].pickerViewText)
                println("####城市id=" + cityItems[options1][option2].id)
//                userInfo?.province = provinceItems[options1].pickerViewText
//                userInfo?.city = cityItems[options1][option2].pickerViewText
                sm_city.setTitleItem(
                    MenuItem(0,
                        cityItems[options1][option2].name,
                        cityItems[options1][option2].id)
                )
                cityId = cityItems[options1][option2].id
                cityName=cityItems[options1][option2].name

            }).isCenterLabel(true).build<AddressInfoPO>()
        pvOptions.setPicker(provinceItems, cityItems)
        pvOptions.show()
    }

}
